package com.wendy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wendy.mapper.MenuMapper;
import com.wendy.model.Menu;
import com.wendy.service.MenuService;
import com.wendy.utils.ResponseUtil;
import com.wendy.web.response.ResponseWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author zhuwending
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public ResponseWrapper getMenuPageList(Map<String, Object> map) {
        String page = String.valueOf(map.get("page"));
        String rows = String.valueOf(map.get("limit"));
        if (StringUtils.isBlank(page) || StringUtils.isBlank(rows)) {
            return ResponseUtil.errorResponse("分页参数不能为空");
        }
        PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(rows));
        PageInfo<Menu> pageInfo = new PageInfo<>(menuMapper.getMenuPageList(map));
        return ResponseUtil.successResponse("page", pageInfo);
    }

    @Override
    public ResponseWrapper addMenu(Menu menu) {
        Menu m = menuMapper.selectMenuByPath(menu.getPath());
        if (m != null) {
            return ResponseUtil.errorResponse("菜单路径重复");
        }
        int row = insert(menu);
        if (row != 1) {
            return ResponseUtil.errorResponse("添加菜单失败");
        }
        return ResponseUtil.successResponse("添加菜单成功");
    }

    @Override
    public ResponseWrapper updateMenu(Menu menu) {
        Menu m = selectByKey(menu.getId());
        if (!menu.getPath().equals(m.getPath())) {
            m = menuMapper.selectMenuByPath(menu.getPath());
            if (m != null) {
                return ResponseUtil.errorResponse("菜单路径已存在");
            }
        }
        int row = update(menu);
        if (row != 1) {
            return ResponseUtil.errorResponse("修改失败");
        }
        return ResponseUtil.successResponse("修改成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper deleteMenu(Long[] idArray) throws Exception {
        if (null == idArray || idArray.length == 0) {
            return ResponseUtil.errorResponse("请选择记录");
        }
        for (Long id : idArray) {
            int row = delete(id);
            if (row != 1) {
                throw new Exception("删除失败");
            }
        }
        return ResponseUtil.successResponse("删除成功");
    }
}
